/*
 * Copyright 2002-2007 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.force4spring.support;

import java.rmi.RemoteException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.force4spring.ForceAccessor;
import org.force4spring.SessionFactoryUtils;
import org.force4spring.SessionHolder;
import org.force4spring.WebServicesCallException;
import org.springframework.dao.DataAccessException;
import org.springframework.transaction.support.TransactionSynchronizationManager;
import org.springframework.ui.ModelMap;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.context.request.WebRequestInterceptor;

import com.sforce.soap.partner.fault.ApiFault;

/**
 * Spring web request interceptor that binds a Force Session to the thread for the
 * entire processing of the request. Intended for the "Open Session in View" pattern,
 * that is, to allow for lazy loading in web views despite the original transactions
 * already being completed.
 *
 * <p>This interceptor makes Force Sessions available via the current thread,
 * which will be autodetected by transaction managers. It is suitable for service layer
 * transactions via {@link org.force4spring.ForceTransactionManager}
 * or {@link org.springframework.transaction.jta.JtaTransactionManager} as well
 * as for non-transactional execution (if configured appropriately).
 *
 * <p>In contrast to {@link OpenSessionInViewFilter}, this interceptor is set up
 * in a Spring application context and can thus take advantage of bean wiring.
 * It inherits common Force configuration properties from
 * {@link org.force4spring.ForceAccessor},
 * to be configured in a bean definition.
 *
 * @author Juergen Hoeller
 * @author Max Rudman
 * @since 04.17.2008
 * @see OpenSessionInViewFilter
 * @see org.force4spring.ForceInterceptor
 * @see org.force4spring.ForceTransactionManager
 * @see org.force4spring.SessionFactoryUtils#getSession
 * @see org.springframework.transaction.support.TransactionSynchronizationManager
 */
public class OpenSessionInViewInterceptor extends ForceAccessor implements WebRequestInterceptor {
	private static final Log log = LogFactory.getLog(OpenSessionInViewInterceptor.class);
	
	/**
	 * Suffix that gets appended to the SessionFactory toString representation
	 * for the "participate in existing session handling" request attribute.
	 * @see #getParticipateAttributeName
	 */
	public static final String PARTICIPATE_SUFFIX = ".PARTICIPATE";


	/**
	 * Create a new OpenSessionInViewInterceptor,
	 * turning the default flushMode to FLUSH_NEVER.
	 * @see #setFlushMode
	 */
	public OpenSessionInViewInterceptor() {
	}

	/**
	 * Open a new Force Session according to the settings of this ForceAccessor
	 * and binds in to the thread via TransactionSynchronizationManager.
	 * @see org.force4spring.SessionFactoryUtils#getSession
	 * @see org.springframework.transaction.support.TransactionSynchronizationManager
	 */
	public void preHandle(WebRequest request) throws DataAccessException {
		if (TransactionSynchronizationManager.hasResource(getSessionFactory())) {
			// Do not modify the Session: just mark the request accordingly.
			String participateAttributeName = getParticipateAttributeName();
			Integer count = (Integer) request.getAttribute(participateAttributeName, WebRequest.SCOPE_REQUEST);
			int newCount = (count != null) ? count.intValue() + 1 : 1;
			request.setAttribute(getParticipateAttributeName(), new Integer(newCount), WebRequest.SCOPE_REQUEST);
		}
		else {
			log.debug("Opening single Force Session in OpenSessionInViewInterceptor");
			ForceSession session = SessionFactoryUtils.getSession(
					getSessionFactory());
			TransactionSynchronizationManager.bindResource(getSessionFactory(), new SessionHolder(session));
		}
	}

	/**
	 * Flush the Force Session before view rendering, if necessary.
	 */
	public void postHandle(WebRequest request, ModelMap model) throws DataAccessException {
		SessionHolder sessionHolder =
				(SessionHolder) TransactionSynchronizationManager.getResource(getSessionFactory());
		log.debug("Flushing single Force Session in OpenSessionInViewInterceptor");
		try {
			flushIfNecessary(sessionHolder.getSession(), false);
		} catch (ApiFault ex) {
			throw convertApiFault(ex);
		} catch (RemoteException re) {
			throw new WebServicesCallException(re);
		}
	}

	/**
	 * Unbind the Force Session from the thread and closes it (in single session
	 * mode), or process deferred close for all sessions that have been opened
	 * during the current request (in deferred close mode).
	 * @see org.springframework.transaction.support.TransactionSynchronizationManager
	 */
	public void afterCompletion(WebRequest request, Exception ex) throws DataAccessException {
		String participateAttributeName = getParticipateAttributeName();
		Integer count = (Integer) request.getAttribute(participateAttributeName, WebRequest.SCOPE_REQUEST);
		if (count != null) {
			// Do not modify the Session: just clear the marker.
			if (count.intValue() > 1) {
				request.setAttribute(participateAttributeName, new Integer(count.intValue() - 1), WebRequest.SCOPE_REQUEST);
			}
			else {
				request.removeAttribute(participateAttributeName, WebRequest.SCOPE_REQUEST);
			}
		}
		else {
			SessionHolder sessionHolder =
					(SessionHolder) TransactionSynchronizationManager.unbindResource(getSessionFactory());
			log.debug("Closing single Force Session in OpenSessionInViewInterceptor");
			SessionFactoryUtils.closeSession(sessionHolder.getSession());
		}
	}

	/**
	 * Return the name of the request attribute that identifies that a request is
	 * already intercepted. Default implementation takes the toString representation
	 * of the SessionFactory instance and appends ".PARTICIPATE".
	 * @see #PARTICIPATE_SUFFIX
	 */
	protected String getParticipateAttributeName() {
		return getSessionFactory().toString() + PARTICIPATE_SUFFIX;
	}

}
